package com.example.administrator.text;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import entity.Update;
import util.AgentIp;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetUtils;
import util.NetWorkstateUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import view.diaLogView.EditionDialog;
import view.diaLogView.RetunDialog;
import view.diaLogView.UploadDialog;

/**
 * 第一个广告登入页
 * 联网的步骤  先连上次连通的ip,不通再连云服务器看是否通  如不通则加载一个portal页面获取ip 再连  如不通加循环本地IP   之前的步骤如有通 都先去
 * 检查版本 在登入登录都走游客接口 状态后台来判断
 */
public class WelComeActvity extends BaseActivity {
    public static final String mWelComeVP = "welComeVP";  //第一次打开app 的标记
    private String mAppState = "";
    private String mToken,mId;
    public String mFwq;
    private WelComeActvity mWelComeActvity;
    private EditionDialog mUpdateDialog;
    private UploadDialog mUploadDialog;
    private RetunDialog mRetunDialog;
    private LayoutInflater mLayoutInflater;
    private List<Update> mUpdateList;
    public ImageView mImageView;
    private boolean mState = true; //点击跳过后会有1、2s 的响应  不让其点击

    @Bind(R.id.image_welcome_string)         ImageView mIView;
    @Bind(R.id.activity_welcomea_im1)        ImageView mIV1;
    @Bind(R.id.activity_welcomea_im2)        ImageView mIV2;
    @Bind(R.id.activity_welcomea_im3)        ImageView mIV3;
    @Bind(R.id.activity_welcomea_iv_view)    ImageView mIVVIEW;
    @Bind(R.id.viewpager_welcome)            ViewPager mVPager;
    @Bind(R.id.activity_welcomea_rl1)        RelativeLayout mRelativeLayout1;
    @Bind(R.id.activity_welcomea_rl2)        RelativeLayout mRelativeLayout2;
    @Bind(R.id.activity_welcomea_ll_view)    LinearLayout mLinearLayout;
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcomea);
        init();
    }

    /**
     * 跳过
     */
    @OnClick(R.id.activity_welcomea_tv)
    void tv(){
        if(mState){
            mState = false;
            update(1);
        }
        HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {@Override public void run() {mState = true;}},2000);
    }

    private void init() {
        HomeUtil.getHemeUtilNew().getStatusBar(this,null);
        mWelComeActvity = this;
        ButterKnife.bind(this);
        mToken = (String) SharedPreferencesUtils.getParam(WelComeActvity.this, HomeUtil.mTokenDB, "");
        mId = (String) SharedPreferencesUtils.getParam(WelComeActvity.this, HomeUtil.mUseridDB, "");
        mAppState = (String) SharedPreferencesUtils.getParam(this,mWelComeVP,"");

        LogUtil.eE("NetWork","..........getNetWorkTeyt........."+NetUtils.getInstance(this).getNetWorkTeyt());
        LogUtil.eE("NetWork","..........getWIFIName........."+getInformation.getNewGetInformation(this).getWIFIName());
            getJudgeIP();
            LogUtil.eE("UrlNew","..........1.........."+Url.getUrlNew().isNotification());
            if(getIntent().getStringExtra("state") !=null){
                if(getIntent().getStringExtra("state").equals("Notification")){
                    LogUtil.eE("UrlNew","........2............"+Url.getUrlNew().isNotification());
                    Url.getUrlNew().setNotification(false);
                    Intent intent = new Intent(HomeActivity.mAction);
                    intent.putExtra("wifi","finish");
                    sendBroadcast(intent);         //发送一个广播
                    Url.getUrlNew().setNotifation_state(1);
                }
            }
    }

    /**
     * 登录
     */
    public void Entry(){
        String jumdString = (String) SharedPreferencesUtils.getParam(WelComeActvity.this, HomeUtil.mHUWePhone, "");
        if(jumdString.equals("")){
            //一般是装app时或 之前没登录得时候走的
            SharedPreferencesUtils.setParam(WelComeActvity.this, HomeUtil.mTokenDB, "null");
            SharedPreferencesUtils.setParam(WelComeActvity.this, HomeUtil.mUseridDB, "0");
            if(Url.getUrlNew().isNotification()){
                HomeUtil.getHemeUtilNew().getTourist(WelComeActvity.this,MyApplication.getApp().getFWQString(),mUploadDialog,mIView,0);
            }else{
                HomeUtil.getHemeUtilNew().getTourist(WelComeActvity.this,MyApplication.getApp().getFWQString(),mUploadDialog,mIView,3);
            }
        }else{

             if(mToken.equals("null")) {
                //一般是登录后 再退出 之后走的方法
                if(Url.getUrlNew().isNotification()){
                    HomeUtil.getHemeUtilNew().getTourist(WelComeActvity.this,MyApplication.getApp().getFWQString(),mUploadDialog,mIView,1);
                }else {
                    HomeUtil.getHemeUtilNew().getTourist(WelComeActvity.this,MyApplication.getApp().getFWQString(),mUploadDialog,mIView,3);
                }
             }else{
                if(Url.getUrlNew().isNotification()){
                    HomeUtil.getHemeUtilNew().getTourist(WelComeActvity.this,MyApplication.getApp().getFWQString(),mUploadDialog,mIView,0);
                }else{
                    HomeUtil.getHemeUtilNew().getTourist(WelComeActvity.this,MyApplication.getApp().getFWQString(),mUploadDialog,mIView,3);
                }
            }
        }
    }

    /**
     * 判断之前ip是否可用
     * type 0 一进来
     */
    public void getJudgeIP(){
        mMap = new HashMap<>();
        if(mId.equals("")){
            mMap.put("userid","0");
        }else {
            mMap.put("userid",mId);
        }
        mMap.put("visitType",1);
        mMap.put("ip",getInformation.getNewGetInformation(this).getI_IP());
        mMap.put("mac",getInformation.getNewGetInformation(this).getIMAC());
        mMap.put("apMac",getInformation.getNewGetInformation(this).getWiFiMac());
        mMap.put("apName",getInformation.getNewGetInformation(this).getWIFIName());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
        mUploadDialog = new UploadDialog(this,"连接中");
        mUploadDialog.show();
        final long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngVersion_isAlive,stringJson,"null","0",time);
        final Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,"null","0",Url.mStirngVersion_isAlive,stirngSign,time);
        mFwq = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mFWQ,"");
        getLogger().info("getJudgeIP--->"+"fwq--"+mFwq+"--type--"+"time"+StringUtil.getStringUtilNew().getTimeInstance()+"...NF_callid..."+map.get("NF_callid")+"..stringJson..."+stringJson);
        GreenTreeNetworkUtil.getInstance().doPost(this,mFwq,2000,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 1) {
                        getLogger().info("getJudgeIP--->onSuccess--->"+"String--"+response);
                      if(jsonObject.getInt("siteAreaid") !=0){
                          MyApplication.getApp().setSiteAreaid(jsonObject.getInt("siteAreaid"));
                          AgentIp.newInstance(WelComeActvity.this).setAltairWifi(true);
                          AgentIp.newInstance(WelComeActvity.this).setNetWorkstate1();
                          agentSuccess(mFwq);
                          if(jsonObject.has("pushIden")){
                               String pushIden =  jsonObject.getString("pushIden");
                               setPushTag(pushIden);
                          }
                      }else {
                          //如果等于0 就再一次去找代理
                          seekSuccess();
                      }
                    }else {
                        seekSuccess();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    seekSuccess();
                }
            }

            @Override public void onFailure(Throwable error) {
                getLogger().info("getJudgeIP--->onFailure--->"+"time"+StringUtil.getStringUtilNew().getTimeInstance()+error);
                seekSuccess();
            }
        });
    }



    /**
     * 设置标签
     * @param tag 标签内容
     */
    private void setPushTag(String tag) {
        String tag1 = (String) SharedPreferencesUtils.getParam(WelComeActvity.this,HomeUtil.AppAltairPushIden,"");
        if(!tag1.equals(tag)){
            SharedPreferencesUtils.setParam(WelComeActvity.this,HomeUtil.AppAltairPushIden,tag);
            SharedPreferencesUtils.setParam(WelComeActvity.this,HomeUtil.AppAltairPushIden_Statr,false);
        }
    }

    /**
     * 先域名访问
     * 判断网络是否可行
     */
    private void domain() {
        HashMap<String,Object> json = new HashMap<>();
        String id = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mUseridDB, "");
        if(id.equals("")){
            json.put("userid",0);
        }else { json.put("userid",id);}

        json.put("apMac",getInformation.getNewGetInformation(this).getWiFiMac());
        json.put("apName",getInformation.getNewGetInformation(this).getWIFIName());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(json); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngVersion_isAlive,stringJson,"null","0",time);
        Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,"null","0",Url.mStirngVersion_isAlive,stirngSign,time);
        getLogger().info("域名domain()--->"+"fwq--"+MyApplication.mFWQIP);
        GreenTreeNetworkUtil.getInstance().doPost(this,MyApplication.mFWQIP,2000,map,new RequestDataCallback() {
            @Override public void onSuccess(String response){
                try {
                    getLogger().info("domain()--->onSuccess()--->"+"String--"+response);
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 1) {
                        SharedPreferencesUtils.setParam(WelComeActvity.this,HomeUtil.appNetWorkstate,true);
                        MyApplication.getApp().setFWQString(Url.getUrlNew().getAppIP());//一般都是4G和域名进去的
                        update(0);
                        if (jsonObject.has("siteAreaid")){
                           MyApplication.getApp().setSiteAreaid(jsonObject.getInt("siteAreaid"));
                        }
                    } else {
                        if(mUploadDialog !=null){mUploadDialog.dismiss();}
                        getToast(getString(R.string.FWQ));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    failSuccess();
                }
            }

            @Override
            public void onFailure(Throwable error) {
                getLogger().info("domain()--->onFailure()--->"+"error...去找代理地址"+error.toString());
                failSuccess();
            }
        });
    }

    /**
     * 寻找代理
     */
    private void seekSuccess(){
        getLogger().info("seekSuccess()--->开始去找代理地址");
        AgentIp.newInstance(WelComeActvity.this).getIp(new AgentIp.OnAgentIpItemClickListener() {
            @Override
            public void onItemClick(String fwq) {
                getLogger().info("seekSuccess()--->onItemClick()代理地址"+fwq);
                if(fwq.equals("没有查到")){
                    mUploadDialog.dismiss();
                    failSuccess();
                }else {
                    agentSuccess(fwq);
                }
            }
        });
    }

    /**
     * 代理成功后的操作
     */
    private void agentSuccess(String fwq){
        if (!fwq.equals(Url.getUrlNew().getAppIP())) {
            SharedPreferencesUtils.setParam(WelComeActvity.this, HomeUtil.mFWQ, fwq);
        }
        MyApplication.getApp().setFWQString(fwq);
        mUploadDialog.dismiss();
        if(mAppState.equals("")){
                NetWorkstateUtil.getInstance().getBrokenNetwork(WelComeActvity.this, new HomeUtil.OnHomeUtilClickListener() {
                    @Override
                    public void onItemClick(String type) {
                        if(type.equals("ok")){
                            AgentIp.newInstance(WelComeActvity.this).setNetWorkstate1();
                        }}}, 1);

            if(MyApplication.getApp().getSiteAreaid() >= 10000 || MyApplication.getApp().getSiteAreaid() == 0){
                mLinearLayout.setVisibility(View.VISIBLE);
                mIVVIEW.setVisibility(View.GONE);
            }else if(MyApplication.getApp().getSiteAreaid() == 1){
                mIVVIEW.setVisibility(View.VISIBLE);
                mIVVIEW.setImageResource(R.mipmap.sz_logo);
            }else if(MyApplication.getApp().getSiteAreaid() == 2){
                mIVVIEW.setVisibility(View.VISIBLE);
                mIVVIEW.setImageResource(R.mipmap.szy_logo);

            }
            update(1);
               /* mRelativeLayout2.setVisibility(View.GONE);
                mRelativeLayout1.setVisibility(View.VISIBLE);
                mIView.setVisibility(View.GONE);
                mIV1.setBackgroundResource(R.mipmap.wel_rectangle);
                mIV2.setBackgroundResource(R.mipmap.wel_dot);
                mIV3.setBackgroundResource(R.mipmap.wel_dot);
                WelComeVPAdapter welcomeVPAdapter = new WelComeVPAdapter(initVpView());
                mVPager.setAdapter(welcomeVPAdapter);
                mVPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        switch (position){
                            case 0:
                                mIV1.setBackgroundResource(R.mipmap.wel_rectangle);
                                mIV2.setBackgroundResource(R.mipmap.wel_dot);
                                mIV3.setBackgroundResource(R.mipmap.wel_dot);
                                break;
                            case 1:
                                mIV1.setBackgroundResource(R.mipmap.wel_dot);
                                mIV2.setBackgroundResource(R.mipmap.wel_rectangle);
                                mIV3.setBackgroundResource(R.mipmap.wel_dot);
                                break;
                            case 2:
                                mIV1.setBackgroundResource(R.mipmap.wel_dot);
                                mIV2.setBackgroundResource(R.mipmap.wel_dot);
                                mIV3.setBackgroundResource(R.mipmap.wel_rectangle);
                                mState = false;
                                update(1);
                                break;
                        }
                    }
                    @Override public void onPageScrollStateChanged(int state) {}
                });*/
        }else {
            if(MyApplication.getApp().getSiteAreaid() >= 10000 || MyApplication.getApp().getSiteAreaid() == 0){
                mLinearLayout.setVisibility(View.VISIBLE);
                mIVVIEW.setVisibility(View.GONE);
            }else if(MyApplication.getApp().getSiteAreaid() == 1){
                mIVVIEW.setVisibility(View.VISIBLE);
                mIVVIEW.setImageResource(R.mipmap.sz_logo);
            }else if(MyApplication.getApp().getSiteAreaid() == 2){
                mIVVIEW.setVisibility(View.VISIBLE);
                mIVVIEW.setImageResource(R.mipmap.szy_logo);

            }
            update(1);
        }
    }

    /**
     * 代理失败后的操作
     */
    private void failSuccess(){
        if(mRetunDialog == null){
            if(!isFinishing()){
                if(mRetunDialog == null){
                    SharedPreferencesUtils.setParam(WelComeActvity.this, HomeUtil.mFWQ,"");
                    mRetunDialog = new RetunDialog(WelComeActvity.this,"wel",1,false);
                    mRetunDialog.show();
                }else {
                    mRetunDialog.show();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        Log.e("WIFL","WelComeActvity()..onDestroy()");
        super.onDestroy();

        if (mMap != null) {
            mMap.clear();
        }

        if (mUpdateList != null) {
            mUpdateList.clear();
        }

        if (mUpdateDialog != null) {
            mUpdateDialog.dismiss();
        }

        if (mUploadDialog != null) {
            mUploadDialog.dismiss();
        }

        if (mRetunDialog != null) {
            mRetunDialog.dismiss();
        }
    }

    public WelComeActvity getApp() {
        return mWelComeActvity;
    }

    /**
     * 更新版本
     * 0 从域名进来
     * 1 从代理进来
     */
    private void update(final int type) {
        mUpdateList = new ArrayList<>();
        mMap = new HashMap<>();
        LogUtil.eE("mFWQString", "   WELC2   " + MyApplication.getApp().getFWQString());
        mMap.put("ver",getInformation.getNewGetInformation(this).getVersion());
        mMap.put("vertype",1);
        mMap.put("appType",1);
        if(type == 0){
            mMap.put("agencyIp","");
        }else{
            if(MyApplication.getApp().getFWQString().contains(":8")){
                String agencyIp = StringUtil.getStringUtilNew().uploadHead(MyApplication.getApp().getFWQString());
                mMap.put("agencyIp",agencyIp);
            }
        }
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngUpdate,stringJson,"null","0",time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,"null","0",Url.mStirngUpdate,stirngSign,time);
        getLogger().info("版本更新update()--->fwq--"+MyApplication.getApp().getFWQString()+"stringJson--"+stringJson);
        GreenTreeNetworkUtil.getInstance().doPost(this,MyApplication.getApp().getFWQString(),1,map1, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                getLogger().info("update()--->onSuccess--->"+"String--"+response);
                HomeUtil.getHemeUtilNew().saveCombo(WelComeActvity.this,0,null);
                Gson gson = new Gson();
                Update update = gson.fromJson(response,Update.class);
                mUpdateList.add(update);
                LogUtil.eE("Gson",response);
                if(update.getCode().equals("1")){
                    if(update.getUs().equals("0")){
                         Entry();
                     //版本可用
                    }else if(update.getUs().equals("1")){
                        mUpdateDialog = new EditionDialog(WelComeActvity.this,mUpdateList,mWelComeActvity);
                        mUpdateDialog.show();
                        //版本不可用
                    }else if(update.getUs().equals("2")){
                        mUpdateDialog = new EditionDialog(WelComeActvity.this,mUpdateList,mWelComeActvity);
                        mUpdateDialog.show();
                    }
                }else {
                    Entry();
                }
            }

            @Override
            public void onFailure(Throwable error) {
                Entry();
            }
        });
    }

    /**
     *  加载适配器所需要的View
     */
    private ArrayList initVpView() {
        ArrayList<View> pageVLispt = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(getApplicationContext());
        for (int i = 0; i < 3; i++) {
            View view = mLayoutInflater.inflate(R.layout.adapter_welcomea_vp,null);
            TextView tv = (TextView) view.findViewById(R.id.adapter_welfare_tv);
            ImageView iv1 = (ImageView) view.findViewById(R.id.adapter_welfare_im1);
            ImageView iv2 = (ImageView) view.findViewById(R.id.adapter_welfare_im2);
            switch (i){
                case 0:
                    tv.setText("更快\n多人使用依旧畅享高速网络");
                    iv1.setImageDrawable(getResources().getDrawable(R.mipmap.welcomea_vp1));
                    iv2.setVisibility(View.GONE);
                    pageVLispt.add(view);
                    break;
                case 1:
                    tv.setText("更有礼券送不停\n首次登录下载赠送50小时上网礼券\n推荐一位好友赠送50小时礼券");
                    iv2.setImageDrawable(getResources().getDrawable(R.mipmap.welcomea_vp1));
                    pageVLispt.add(view);
                    iv1.setVisibility(View.GONE);
                    break;
                case 2:
                    tv.setText("更安全\nApp登录使用，保障你的信息安全");
                    iv2.setImageDrawable(getResources().getDrawable(R.mipmap.welcomea_vp3));
                    pageVLispt.add(view);
                    iv1.setVisibility(View.GONE);
                    break;
            }

        }
        return pageVLispt;
    }
}
